const { Router } = require("express");
const Admin = require("../model/Admin");

const router = new Router();


// 新增管理员
router.post("/", async (req, res) => {
  const { name, password,confirmPassword } = req.body;
  
  if (!name) {
    res.status(400).json({ message: "用户名不能为空！" });
    return;
  }

  if (!password ) { 
    return res.status(400).json({ message: "密码不能为空" });
  }
  if (!confirmPassword ) { 
    return res.status(400).json({ message: "确认密码不能为空" });
  }
  await Admin.create({
    name: name,
    createTime: new Date().getTime(),
    password,
    confirmPassword
  });
  res.json({ message: "新增成功！" });
});

//根据创建时间获取管理员列表
router.get("/", async (req, res) => {
  const page = Number(req.query.page);
  const count = Number(req.query.count);
  if (!page || !count) {
    res.status(400).json({ message: "参数不能为空！" });
    return;
  }
  const [total, data] = await Promise.all([
    //查询总数
    Admin.countDocuments(),
    // 查询当前页的数据
    Admin.find()
    .sort({ createTime: -1 })
    .skip((page - 1) * count)
    .limit(count)
  ]);
  res.json({total, data});
});
module.exports = router;